<script setup lang="ts">
import {ref, watchEffect} from 'vue'
import {Refresh, Search} from '@element-plus/icons-vue'
import axios from 'axios'
import { ElMessage,ElMessageBox } from 'element-plus'
// 订单状态类型
type OrderStatus = 0 | 1 | 2 | '全部'
const selectedStatus = ref<OrderStatus>('全部')
const orders = ref<any[]>([]) // 订单数据
const commentDialogVisible = ref(false)
const currentOrderId = ref<number | null>(null)
const rating = ref(0)
const comment = ref('')
const detailDialogVisible = ref(false)
const currentOrderDetail = ref<any>({})
const searchDialogVisible = ref(false)
const searchForm = ref({
  orderId: '',
  model: '',
  dateRange: [],
  serviceName: ''
})
const formatDate = (date: Date | undefined): string | undefined => {
  if (!date) return undefined
  return date.toISOString().replace('T', ' ').replace(/\..+/, '')
}
// 新增搜索方法
const handleAdvancedSearch = () => {
  searchDialogVisible.value = true
}

const submitSearch = async () => {
  try {
    const params = {
      id: searchForm.value.orderId || undefined,
      model: searchForm.value.model || undefined,
      serviceName: searchForm.value.serviceName || undefined,
      startDate: searchForm.value.dateRange[0] ? formatDate(new Date(searchForm.value.dateRange[0])) : undefined,
      endDate: searchForm.value.dateRange[1] ? formatDate(new Date(searchForm.value.dateRange[1])) : undefined,
      status: selectedStatus.value === '全部' ? undefined : selectedStatus.value
    }

    const response = await axios.get('/api/appointment/user/search', { params })
    orders.value = response.data.data
    searchDialogVisible.value = false
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败')
  }
}

const handleViewDetail = (order: any) => {
  currentOrderDetail.value = order
  detailDialogVisible.value = true
}
const statusMap = [
  { text: '待确认', type: 'warning' },//0
  { text: '维修中', type: 'primary' },//1
  { text: '已完成', type: 'success' }//2
]

// 获取订单列表
const fetchOrders = async () => {
  try {
    const status = selectedStatus.value === '全部' ? undefined : selectedStatus.value
    const url = typeof status === 'number'
        ? `/api/appointment/user/list?status=${status}`
        : '/api/appointment/user/list'
    const response = await axios.get(url)
    orders.value = response.data.data
    console.log(orders.value)
  } catch (error) {
    console.error('获取订单失败:', error)
  }
}
// 监听筛选状态变化
watchEffect(() => {
  fetchOrders()
})
const handleComment = (orderId: number) => {
  // 这里添加评论逻辑
  console.log('评论订单', orderId)
  commentDialogVisible.value = true
  currentOrderId.value = orderId
}
const submitComment = async () => {
  try {
    if (rating.value === 0) {
      ElMessage.warning('请先评分')
      return
    }

    await axios.post('/api/review/create', {
      orderId: currentOrderId.value,
      rating: rating.value,
      comment: comment.value
    })

    ElMessage.success('评价成功')
    commentDialogVisible.value = false
    await fetchOrders()
    // 重置表单
    rating.value = 0
    comment.value = ''
  } catch (error) {
    ElMessage.error('评价失败')
  }
}
// 新增对话框状态
const commentViewDialogVisible = ref(false)
const currentComment = ref({
  rating: 0,
  comment: ''
})
// 新增查看评论方法
const handleViewComment = async (orderId: number) => {
  try {
    const response = await axios.get('/api/review/get', {
      params: { orderId }
    })
    currentComment.value = response.data.data
    commentViewDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取评论详情失败')
  }
}
const handleCancel = async (orderId: number) => {
  try {
    await ElMessageBox.confirm('确定要取消该预约吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })


    const response =  await axios.delete('/api/appointment/user/cancel', {
      params: { orderId }
    })
    if (response.status === 200) {
      ElMessage.success('取消预约成功')
      await fetchOrders() // 刷新订单列表
    } else {
      ElMessage.error('取消预约失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消预约错误:', error) // 添加错误日志
    }
  }
}
</script>

<template>
  <div class="order-management">
    <el-container>
      <el-aside width="260px" class="sidebar">
        <!-- 订单筛选区 -->
        <div class="filter-section">
          <h3 class="filter-title">订单状态</h3>
          <el-radio-group v-model="selectedStatus" class="status-group">
            <el-radio-button label="全部" value="全部"/>

          </el-radio-group>
          <el-radio-group v-model="selectedStatus" class="status-group">
            <el-radio-button label="待确认" :value="0"/>

          </el-radio-group>
          <el-radio-group v-model="selectedStatus" class="status-group">
            <el-radio-button label="维修中" :value="1"/>

          </el-radio-group>
          <el-radio-group v-model="selectedStatus" class="status-group">
            <el-radio-button label="已完成" :value="2"/>
          </el-radio-group>


          <el-divider class="divider"/>

          <div class="quick-actions">
            <el-button type="primary" class="action-button" @click="fetchOrders">
              <el-icon>
                <Refresh/>
              </el-icon>
              刷新列表
            </el-button>
            <el-button class="action-button" @click="handleAdvancedSearch">
              <el-icon>
                <Search/>
              </el-icon>
              高级搜索
            </el-button>
          </div>
        </div>
      </el-aside>

      <el-main class="main-content">
        <!-- 订单列表区 -->
        <div class="order-list">
          <el-card
              v-for="(order, index) in orders"
              :key="index"
              class="order-item"
              shadow="hover"
              :body-style="{ padding: '16px 20px' }"
          >
            <template #header>
              <div class="order-header">
                <div class="order-info">
                  <span class="order-number">订单号：{{ order.id }}</span>
                  <el-tag :type="statusMap[order.status].type">
                    {{ statusMap[order.status].text }}
                  </el-tag>
                </div>
                <div class="order-actions">
                  <el-button
                      v-if="order.status === 0"
                      type="danger"
                      size="small"
                      @click="handleCancel(order.id)"
                  >
                    取消预约
                  </el-button>
                  <el-button
                      v-if="order.status === 2 && order.commentStatus === 0"
                      type="success"
                      size="small"
                      @click="handleComment(order.id)"
                  >
                    立即评价
                  </el-button>
                  <el-button
                      v-if="order.status === 2 && order.commentStatus === 1"
                      type="info"
                      size="small"
                      plain
                      @click="handleViewComment(order.id)"
                  >
                    已评论
                  </el-button>
                  <el-button type="text"
                             class="action-link"
                             @click="handleViewDetail(order)"
                  >查看详情</el-button>
                </div>
              </div>
            </template>
            <div class="order-content">
              <p>车型：{{ order.model }}</p>
              <p>预约时间：{{ order.formattedAppointmentTime }}</p>
              <p>服务项目：{{ order.serviceName }}</p>
            </div>
          </el-card>
        </div>
      </el-main>
    </el-container>
  </div>
  <el-dialog
      v-model="commentDialogVisible"
      title="服务评价"
      width="500px"
  >
    <el-form label-width="80px">
      <el-form-item label="服务评分" >
        <el-rate
            v-model="rating"
            show-text
            :texts="['极差', '失望', '一般', '满意', '惊喜']"
        />
      </el-form-item>
      <el-form-item label="评价内容">
        <el-input
            v-model="comment"
            type="textarea"
            :rows="4"
            placeholder="请输入您的服务体验"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="commentDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitComment">提交评价</el-button>
    </template>
  </el-dialog>
  <!-- 新增查看评论对话框 -->
  <el-dialog
      v-model="commentViewDialogVisible"
      title="评价详情"
      width="500px"
  >
    <el-form label-width="80px">
      <el-form-item label="服务评分">
        <el-rate
            v-model="currentComment.rating"
            disabled
            show-text
            :texts="['极差', '失望', '一般', '满意', '惊喜']"
        />
      </el-form-item>
      <el-form-item label="评价内容">
        <el-input
            v-model="currentComment.comment"
            type="textarea"
            :rows="4"
            readonly
            class="readonly-comment"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="commentViewDialogVisible = false">关闭</el-button>
    </template>
  </el-dialog>
  <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="500px"
  >
    <el-form label-width="80px">
      <el-form-item label="订单号">
        <el-input v-model="currentOrderDetail.id" readonly />
      </el-form-item>
      <el-form-item label="车型">
        <el-input v-model="currentOrderDetail.model" readonly />
      </el-form-item>
      <el-form-item label="预约时间">
        <el-input v-model="currentOrderDetail.formattedAppointmentTime" readonly />
      </el-form-item>
      <el-form-item label="服务项目">
        <el-input v-model="currentOrderDetail.serviceName" readonly />
      </el-form-item>
      <!-- 可根据实际数据字段添加更多内容 -->
    </el-form>
    <template #footer>
      <el-button @click="detailDialogVisible = false">关闭</el-button>
    </template>
  </el-dialog>
  <el-dialog
      v-model="searchDialogVisible"
      title="高级搜索"
      width="600px"
  >
    <el-form :model="searchForm" label-width="100px">
      <el-form-item label="订单号">
        <el-input v-model="searchForm.orderId" placeholder="请输入订单号"/>
      </el-form-item>
      <el-form-item label="车型">
        <el-input v-model="searchForm.model" placeholder="请输入车型"/>
      </el-form-item>
      <el-form-item label="服务项目">
        <el-input v-model="searchForm.serviceName" placeholder="请输入服务项目"/>
      </el-form-item>
      <el-form-item label="预约时间">
        <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="searchDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitSearch">搜索</el-button>
    </template>
  </el-dialog>
</template>


<style scoped>
:deep(.el-input.is-readonly .el-input__inner) {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #606266;
  cursor: default;
}
.readonly-comment {
  :deep(.el-textarea__inner) {
    background-color: #f5f7fa;
    cursor: default;
  }
}
.order-management {
  height: 100vh; /* 确保容器高度占满视口 */
}
.order-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}
.sidebar {
  position: fixed;
  left: 0;
  top: 60px; /* 与Header高度一致 */
  bottom: 0;
  width: 260px;
  overflow-y: auto; /* 仅侧边栏可滚动 */
  background: #ffffff;
  padding: 20px;
  border-right: 1px solid #e4e7ed;
}

.status-group {
  display: flex;
  flex-direction: column;
  margin-top: 10px;
  width: 220px;
}
:deep(.el-radio-button .el-radio-button__inner) {
  width: 220px !important;
  text-align: center;
}

.divider {
  margin: 20px 0;
  border-color: #e4e7ed;
}
.el-main{
  margin-left: 260px;
  height: 100%;
  overflow-y: auto; /* 仅主内容区可滚动 */
  padding: 24px;
  background-color: #f5f7fa;
}
.quick-actions {
  display: flex;
  flex-direction: column;
}

.action-button {
  justify-content: center;
  margin-bottom: 10px;
  width: 100%;
  margin-left: 0;
}

.action-button .el-icon {
  margin-right: 8px;
}

/* 主内容区样式 */
.main-content {
  padding: 24px;
  background-color: #f5f7fa;
}

.order-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
}

.order-item {
  border-radius: 8px;
  background-color: #ffffff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease-in-out;
}

.order-item:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.order-number {
  font-weight: 600;
  color: #303133;
}

.status-tag {
  font-size: 12px;
  font-weight: 500;
}

.order-actions .action-link {
  color: #409eff;
  font-size: 14px;
  font-weight: 500;
}

.order-actions .action-link:hover {
  text-decoration: underline;
}

.order-content p {
  margin: 8px 0;
  font-size: 14px;
  line-height: 1.6;
}

.label {
  color: #606266;
  font-weight: 500;
  margin-right: 8px;
}

.value {
  color: #303133;
  font-weight: 500;
}
</style>


